﻿using System;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Linq;

namespace SimpleHTMLRender
{
    /// <summary>
    /// Helper extensions that one can add onto HtmlNode for
    /// various operations.
    /// </summary>
    static public class HtmlExtensions
    {
        /// <summary>
        /// Finds all child-nodes starting from the base node that satisfy some test.
        /// This is sort-of like SelectNodes, but it isn't cursor operated, it is recursive operated.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<HtmlNode> ScanSubNodes(this HtmlNode baseNode, Func<HtmlNode, bool> testForReturn, Func<HtmlNode, bool> dontLookInside = null)
        {
            if (baseNode.HasChildNodes)
            {
                foreach (var item in baseNode.ChildNodes)
                {
                    if (testForReturn(item))
                    {
                        yield return item;
                    }
                    else
                    {
                        if (dontLookInside == null || !dontLookInside(item))
                        {
                            foreach (var subitem in item.ScanSubNodes(testForReturn))
                            {
                                yield return subitem;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Scan for a particular named node in the tree - use recusion instead of the
        /// usual SelectNodes method which is cursor like.
        /// </summary>
        /// <param name="nodename"></param>
        /// <param name="baseNode"></param>
        /// <returns></returns>
        public static IEnumerable<HtmlNode> ScanSubNodes(this HtmlNode baseNode, string nodename)
        {
            return baseNode.ScanSubNodes(n => n.Name == nodename);
        }

        /// <summary>
        /// Returns true if there is a node "below" this one that is called nodename. Eg, does the
        /// "a" wrap a "img"?
        /// </summary>
        /// <param name="baseNode"></param>
        /// <param name="nodename"></param>
        /// <returns></returns>
        public static bool ContainsTag(this HtmlNode baseNode, string nodename)
        {
            return baseNode.ScanSubNodes(nodename).Any();
        }

        /// <summary>
        /// Execute an action over a sequence. Unlike Apply, this actualy does move through the
        /// sequence.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="doIt"></param>
        public static void Execute<T>(this IEnumerable<T> source, Action<T> doIt)
        {
            foreach (var item in source)
            {
                doIt(item);
            }
        }

        /// <summary>
        /// Try to repair table html. Specifically, look for and fix up the following errors:
        ///   - <tr> with no closing </tr>
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static HtmlNode FixUpTableHtml(this HtmlNode tableNode)
        {
            if (tableNode.Name == "table")
            {
                return RemoveDuplicateTags(FixUpMatchingTag(FixUpMatchingTag(tableNode, "tr"), "td"), "td");
            }
            else
            {
                return tableNode;
            }
        }

        /// <summary>
        /// If we find a duplicate closing tag, remove it. :-) Lets hope this doesn't
        /// break anything!
        /// </summary>
        /// <param name="htmlNode"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        private static HtmlNode RemoveDuplicateTags(HtmlNode htmlNode, string tag)
        {
            HtmlNode result = htmlNode.Clone();

            string tagH = "</" + tag + ">";
            result.InnerHtml = htmlNode.InnerHtml.Replace(tagH + tagH, tagH);

            return result;
        }

        /// <summary>
        /// Try to fix up html by looking for matching tags
        /// </summary>
        /// <param name="tableNode"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        private static HtmlNode FixUpMatchingTag(HtmlNode tableNode, string nodeName)
        {
            HtmlNode resultNode = tableNode.Clone();
            bool startsWithTag = tableNode.InnerHtml.StartsWith("<" + nodeName);
            string[] allTRs = tableNode.InnerHtml.Split(new string[] { "<" + nodeName }, StringSplitOptions.RemoveEmptyEntries);
            string result = "";
            foreach (var item in allTRs)
            {
                if (startsWithTag)
                {
                    result += "<" + nodeName + item;
                    if (!item.Contains("</" + nodeName))
                    {
                        result += "</" + nodeName + ">";
                    }
                }
                else
                {
                    result += item;
                }
                startsWithTag = true;
            }
            resultNode.InnerHtml = result;
            return resultNode;
        }

        /// <summary>
        /// Do our best to make some html text clean and ready for use by the real work.
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string CleanHTMLText(this string html)
        {
            string result = html;

            result = result.Replace("\n", " ");
            result = result.Replace("&lt;", "<");
            result = result.Replace("&gt;", ">");
            result = result.Replace("&nbsp;", " ");
            result = result.Replace("&nbsp", " "); // More common than you think! :-)
            result = result.Replace("\u000c", "fi"); // A ligature!

            ///
            /// Replace any control characters with a space!
            /// 

            for (int i = 0; i < result.Length; i++)
            {
                if (char.IsControl(result[i]))
                {
                   result = result.Replace(result[i], ' ');
                }
            }

            ///
            /// Kill off leading and trailing white space
            /// 

            result = result.Trim();

            /// Kill off all multiple spaces

            while (result.Contains("  "))
            {
                result = result.Replace("  ", " ");
            }

            return result;
        }

        /// <summary>
        /// Looks through a given html collection and tries to find the nodes that are title..
        /// the first one it returns the inner text for.
        /// </summary>
        /// <returns></returns>
        public static string ExtractHTMLTitle(this HtmlNode rootNode)
        {
            var titleNodes = rootNode.SelectNodes("//title");
            string title = null;
            if (titleNodes != null && titleNodes.Count > 0)
            {
                title = titleNodes[0].InnerText.CleanHTMLText();
                if (title.Length == 0)
                {
                    title = null;
                }
            }
            return title;
        }
    }
}
